import fs from 'fs';
import path from 'path';
import webpack from 'webpack';
import convert from 'koa-convert';
import devMiddleware from 'koa-webpack-dev-middleware';
import hotMiddleware from 'koa-webpack-hot-middleware';
// import {hotMiddleware,devMiddleware} from 'koa-webpack-middleware';
//
import chokidar from 'chokidar';
import { app, creatServer } from './app';
import { getDevConfig } from '@/webpack/webpack.config.babel';

const webpackConfig = getDevConfig();
const compiler = webpack(webpackConfig);

// Webpack hook event to write html file into `/views/dev` from `/views/tpl` due to server render
compiler.plugin('emit', (compilation, callback) => {
  const assets = compilation.assets;
  let file, data;

  Object.keys(assets).forEach(key => {
    if (key.match(/\.html$/)) {
      file = path.resolve(__dirname, key);
      data = assets[key].source();
      fs.writeFileSync(file, data);
      console.log('template = ' + key);
    }
  });
  callback();
});

const devMiddlewareInstance = devMiddleware(compiler, {
  //文件的输出路径,由于是都是在内存中执行的, 所以是看不到具体的文件的
  publicPath: webpackConfig.output.publicPath,
  //是否开启热加载功能
  hot: true,
  noInfo: true,
  //是否记录浏览器历史,配合react-router使用
  historyApiFallback: true,
  stats: {
    // 用颜色标识
    colors: true
  },
  watchOptions: {
    aggregateTimeout: 300,
    poll: true
  },
});

const hotMiddlewareInstance = hotMiddleware(compiler, {
  log: console.log,
  path: '/__webpack_hmr',
  heartbeat: 10 * 1000
});

// app.use(devMiddlewareInstance);
// app.use(hotMiddlewareInstance);

app.use(convert(devMiddlewareInstance));
app.use(convert(hotMiddlewareInstance));

creatServer();

// const watcher = chokidar.watch([
// 	path.join(__dirname, '../app'),
// 	// path.join(__dirname, '../server')
// ]);
// watcher.on('ready', () => {
// 	watcher.on('all', (e, p) => {
// 		console.info('Clearing module cache');
// 		Object.keys(require.cache).forEach(function(id) {
// 			if (/[\/\\](app|server)[\/\\]/.test(id)) {
// 				console.log(id);
// 				delete require.cache[id];
// 			}
// 		});
// 	});

// });
